﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Deployment.WindowsInstaller;
using Umbrella.Net.Contracts;
using Umbrella.Whs;

namespace Umbrella.Whs.SharePoint
{
    public sealed class InstallationPackagesManager
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(InstallationPackagesManager));
        private UmbrellaServiceClientFactory _factory;

        public IEnumerable<SharePointInstallationFile> GetInstallationFileList()
        {
            var c = _factory.CreateChannel();

            var r = c.GetSharePointInstallationFiles(UmbrellaVersion.SharePointVersionBuild);

            // download url overriden?
            if (!string.IsNullOrEmpty(Properties.Settings.Default.DebugOverrideSharePointDownloadDir))
            {
                try
                {
                    // create new base url
                    var baseUrl = new Uri(
                        Properties.Settings.Default.DebugOverrideSharePointDownloadDir,
                        UriKind.Absolute
                        );

                    // override urls
                    r = r.Select(o =>
                        {
                            var url = new Uri(o.ZipDownloadUrl);
                            var filename = url.Segments[url.Segments.Length - 1];

                            o.ZipDownloadUrl = new Uri(baseUrl, filename).ToString();

                            return o;
                        });
                }
                catch (Exception x)
                {
                    _log.Error("Failed to override installation package download urls; clear DebugOverrideSharePointDownloadUrl setting!", x);

                    throw;
                }
            }

            // done
            return r;
        }

        public IEnumerable<SharePointLanguage> GetLanguageList()
        {
            var c = _factory.CreateChannel();

            return c.GetSharePointLanguages();
        }

        public IList<SharePointInstallationFile> GetInstalledLanguagePacks()
        {
            var files = GetInstallationFileList();
            var l = new List<SharePointInstallationFile>();

            // check languages
            foreach (var ip in files)
            {
                try
                {
                    using (var s = Installer.OpenProduct(ip.ProductCode.ToString()))
                    {
                        if (s != null)
                            l.Add(ip);
                    }
                }
                catch (Exception x)
                {
                    _log.Warn("Failed to open SharePoint language pack from MSI database: " + ip.LanguageLCID, x);
                }
            }

            return l.AsReadOnly();
        }

        public DirectoryInfo GetExtractionDirectory(SharePointInstallationFile ip)
        {
            return new DirectoryInfo(
                Path.Combine(InstallationManager.InstallationTempDir, ip.LanguageLCID.ToString())
                );
        }

        public DirectoryInfo GetCoreExtractionDirectory()
        {
            return new DirectoryInfo(
                Path.Combine(InstallationManager.InstallationTempDir, InstallationManager.RootLanguageLCID.ToString())
                );
        }

        public InstallationPackagesManager()
        {
            _factory = new UmbrellaServiceClientFactory();
        }
    }
}
